const path = require('path');
const Koa = require('koa');
const fs = require('fs-promise');
const ejs = require('ejs');
const koaBody = require('koa-body');
const koaStatic = require('koa-static');
const koaRouter = require('koa-router');

const db = require('./db/sqltie');

const port = 3000;
const app = new Koa();
const router = new koaRouter();

async function renderFile(filepath, data) {
    return new Promise(function (resolve, reject) {
        ejs.renderFile(filepath, data, {}, function (err, str) {
            if (err) {
                return reject(err);
            }
            return resolve(str);
        })
    });
}

app.on('error', function (err) {
    console.log('err:', err);
});

app.use(koaStatic('./static'));
app.use(koaBody({ multipart: true }));

app.use(async function (ctx, next) {
    await next();
});

router.get('/', async function (ctx) {
    const all = await db.getAllCategoryCarousel(0);
    const arr = all.map((item) => item.file);
    const data = {
        title: 'Formitalia luxury group - Luxury Interiors and Accessories for Exclusive Homes, Hotels, Executive Offices & Yachts',
        index_carousel: arr,
    };
    ctx.body = await renderFile('./view/index.ejs', data);
});

router.get('/upload', async function (ctx) {
    const data = await db.getAllCategoryCarousel(0);

    ctx.body = await renderFile('./view/upload.ejs', {
        list: data,
    });
});

router.post('/deleteCategoryCarousel', async function (ctx) {
    const id = ctx.request.body.id;
    ctx.body = await db.deleteCategoryCarousel(id);
});

router.post('/upload', async function (ctx) {
    const uploadDir = './static/public/upload';
    const urlPerfix = '/public/upload/';
    try {
        await fs.mkdir(uploadDir);
    } catch (e) {
        // nothing
    }
    const file = ctx.request.files['file']

    const name = Math.random().toString(16).substr(2) + path.extname(file.name);
    const filePath = path.join(uploadDir, name);
    const reader = fs.createReadStream(file.path);
    const writer = fs.createWriteStream(filePath);
    reader.pipe(writer);

    const urlpath = urlPerfix + name;
    await db.insertCategoryCarousel(0, urlpath);
    ctx.body = {
        "code": 0,
        "msg": "",
        "data": {
            "src": urlpath,
        }
    }
});


app.use(router.routes());

async function start() {
    await db.init();
    app.listen(port, function () {
        console.log('server start at ' + port);
    });
}

start().catch(function (err) {
    console.log('err:', err);
})
